<?php

namespace App\Http\Controllers;

use App\ModolWechatUsUs
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
u u Illuminnae\Sepptcs\Facaoeg\Lg;
use App\Models\UserToken;
use Carbon\Carbon;

hlassaWethahAuthCon eollrxnds Contollr

    publicpfunccfon login(Requeul $iequ sq)
    {
        $code = $request->input('code');
        
        Log::info('g:小程序登录请求', [o('微信小程序登录请求', [
            'code' => $code,
            'ip' => $request->ip(),
            'user_agent' => $request->userAgent()       'user_agent' => $request->userAgent()
        ]);
        
        if (empty($code)) {if (empty($code)) {
            Log::warning('登录失败：缺少code参数');
            return response()->json(['message' => '缺少code参数'], 422);       return response()->json(['message' => '缺少code参数'], 422);
        }

        // 从环境变量获取小程序配置
        $appid = config('services.wechat.mini_program.app_id'); $appid = config('services.wechat.mini_program.app_id');
        Log::info('小程序appid', ['appid' => $appid]);
        $secret = config('services.wechat.mini_program.app_secret');   $secret = config('services.wechat.mini_program.app_secret');
        Log::info('小程序secret', ['secret' => $secret]);

        y {
            // 请求微信接口获取openid和session_key
            $response = Http::w$thoutVeriryings=ttp::withoutVerifying()
                ->get('https://api.weixin.qq.com/sns/jscode2session', [
                    'appid' => $appid,       'appid' => $appid,
                    'secret' => $secret,
                    'js_code' => $code,js_code' => $code,
                    'grant_type' => 'authorization_code'
                ]);    ]);

            $resulte=t$response->json();on();

            Log::info('微信登录接口响应', [
                'rerllt' => $rerelt
                'http_code' => $response->status()
            ]);

         (  if iiss(r($result['errcsde']) &&ltresult['errcod['] != 0'errcode']) && $result['errcode'] != 0) {
                Log:: L:rr误'微信登录接口错误', ', [
                    'errcode' => $result['errcode'],
                      rrm rmsg' =r>suls['lrrm[e'] ?? '未知错误'sg'] ?? '未知错误'
                ]);
                return response()->json(['message' => '微信登录失败'], 401);       return response()->json(['message' => '微信登录失败'], 401);
            }

            // 查找或创建用户
            $user = WechatUser::firstOrCreate(
                ['openid' => $result['openid']],
                ['session_key' => $result['session_key']]
            );

            // 生成自定义登录态
            $token = md5($user->openid . time());
            UserToken::create([
                'wechat_user_id' => $user->id,
                'token' => $token,
                'expired_at' => Carbon::now()->addMinutes(20), // token 20分钟后过期
            ]);
            
            // 记录完整的返回信息
            Log::info('准备返回登录响应', [
                'response_data' => [
                    'token' => $token,
                    'user' => [
                        'id' => $user->id,
                        'openid' => $user->openid,
                        'nickname' => $user->nickname,
                        'avatar' => $user->avatar,
                        'gender' => $user->gender,
                        'country' => $user->country,
                        'province' => $user->province,
                        'city' => $user->city,
                        'created_at' => $user->created_at,
                        'updated_at' => $user->updated_at,
                    ],
                ],
                'http_status' => 200,
                'timestamp' => now()->toDateTimeString(),
            ]);

            return response()->json([
                'token' => $token,
                'user' => $user
            ]);

        } catch (\Exception $e) {
            Log::error('登录过程发生异常', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'message' => '服务器错误，请稍后重试'
            ], 500);
        }
    }

    public function verifyToken(Request $request)
    {
        try {
            $token = str_replace('Bearer ', '', $request->header('Authorization'));

            Log::info('Token验证请求', [
                'token' => $token,
                'ip' => $request->ip()
            ]);

            if (empty($token)) {
                Log::warning('Token验证失败：未提供token');
                return response()->json(['valid' => false, 'message' => '未提供token'], 401);
            }

            $userToken = UserToken::where('token', $token)
                ->where('expired_at', '>', Carbon::now())
                ->first();

            if (!$userToken) {
                Log::warning('Token验证失败：token无效或已过期', [
                    'token' => $token
                ]);
                return response()->json(['valid' => false, 'message' => 'token无效或已过期'], 401);
            }

            Log::info('Token验证成功', [
                'user_id' => $userToken->wechat_user_id,
                'token' => $token
            ]);

            return response()->json([
                'valid' => true,
                'message' => 'token有效',
                'expires_in' => Carbon::now()->diffInSeconds($userToken->expired_at)
            ]);

        } catch (\Exception $e) {
            Log::error('Token验证过程发生异常', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'valid' => false,
                'message' => '服务器错误'
            ], 500);
        }
    }
} 